$().ready(function() {
	loadReimUserid();
	loadDeptId();
	loadReim();
	validateRule();
	laydate({
		elem : '#reimDate'
	});
});

$.validator.setDefaults({
	submitHandler : function() {
		save();
	}
});

/**
 * 报销人
 */
var reimUseridlist = []
function loadReimUserid(){
	var html = "";
	$.ajax({
		url : '/sys/user/getAlllist',
		success : function(data) {
			//加载数据
			reimUseridlist = data
			for (var i = 0; i < data.length; i++) {
				html += '<option value="' + data[i].value + '">' + data[i].name + '</option>'
			}
			$(".chosen-select-reimUserid").append(html);
			$(".chosen-select-reimUserid").chosen({
				maxHeight : 200
			});
			//点击事件
			$('.chosen-select-reimUserid').on('change', function(e, params) {
				var opt = {
					query : {
						type : params.selected,
					}
				}
				$('#exampleTable').bootstrapTable('refresh', opt);
			});
		}
	});
}

//部门
var deptIdlist = []
function loadDeptId(){
	var html = "";
	$.ajax({
		url : '/system/sysDept/list',
		success : function(data) {
			deptIdlist = data
			//加载数据
			for (var i = 0; i < data.length; i++) {
				html += '<option value="' + data[i].value + '">' + data[i].name + '</option>'
			}
			$(".chosen-select-dept").append(html);
			$(".chosen-select-dept").chosen({
				maxHeight : 200
			});
			//点击事件
			$('.chosen-select-dept').on('change', function(e, params) {
				var opt = {
					query : {
						type : params.selected,
					}
				}
				$('#exampleTable').bootstrapTable('refresh', opt);
			});
		}
	});
}

//项目列表
function loadReim(){
	var html = "";
	$.ajax({
		url : '/itm/project/getProjectlist',
		success : function(data) {
			//加载数据
			for (var i = 0; i < data.length; i++) {
				html += '<option value="' + data[i].id + '">' + data[i].name + '</option>'
			}
			$(".chosen-select-project").append(html);
			$(".chosen-select-project").chosen({
				maxHeight : 200
			});
			//点击事件
			$('.chosen-select-project').on('change', function(e, params) {
				var opt = {
					query : {
						type : params.selected,
					}
				}
				$('#exampleTable').bootstrapTable('refresh', opt);
			});
		}
	});
}

function save() {
}
function validateRule() {
	var icon = "<i class='fa fa-times-circle'></i> ";
	$("#signupForm").validate({
		rules : {
			deptId : {
				required : true
			},
			reimDate:{
				required : true
			},
			reimUserid:{
				required : true
			},
			reimAmount:{
				required : true
			},
			reimNumber:{
				required : true
			},
			remark:{
				required : true
			}
		},
		messages : {
			deptId : {
				required : icon + "请选择部门"
			},
			reimDate:{
				required : icon + "请选择报销日期"
			},
			reimUserid:{
				required : icon + "请选择报销人"
			},
			reimAmount:{
				required : icon + "请输入报销金额"
			},
			reimNumber:{
				required : icon + "请输入报销单号"
			},
			remark:{
				required : icon + "请输入摘要信息"
			}
		}
	})
}

$('#deviceweihu-table').next().find('.layui-table-body').find("table").find("tbody").children("tr").on(
	'dblclick',
	function () {
		var id = JSON.stringify($('#deviceweihu-table').next().find('.layui-table-body').find("table").find(
			"tbody").find(".layui-table-hover").data('index'));
		var obj = res.data[id];
		//fun.openLayer(obj);
	})

layui.use('laydate', function () {
	var laydate = layui.laydate;
	//执行一个laydate实例
	laydate.render({
		elem: '#test1', //指定元素
		value: new Date()
	});
});

layui.use('element', function () {
	var element = layui.element;
});
var selectData = {};
var opentls={
	elem: '#demo',
	cols: [
		[ //标题栏
			{
				type: 'checkbox',
				fixed: 'left'
			},
			{
				field: 'id',
				title: 'ID',
				type: 'numbers'
			},
			{
				field: 'projectId',
				title: '项目',
				templet: '#projectId'
			},
			{
				field: 'amountTypeid',
				title: '费用类型',
				templet: '#amountTypeid'
			},
			{
				field: 'reimPrice',
				title: '金额',
				edit: 'text'
			},
			{
				field: 'invoiceType',
				title: '发票类型',
				templet: '#invoiceType'
			},
			{
				field: 'taxRate',
				title: '税率',
				edit: 'text'
			},
			/*{
				field: 'notTaxPrice',
				title: '不含税金额',
				edit: 'text'
			},*/
			{
				field: 'specRemark',
				title: '特殊说明',
				edit: 'text'
			}, {
				field: 'remark',
				title: '行备注',
				edit: 'text'
			}
		]
	],
	data: [{
		amountTypeid:22,
		invoiceType:6,
		taxRate:0
	}],
	limit:9999,
	even: true
};

function tableSelect(layui,options){
	/*
        dong---支持开启关闭 select 功能 ----dong
        renderTable(name,open)
        open:false/true
    */
	var that = this
	this.options = options

	this.url = null
	this.eleSelect = null
	this.selectName = null
	this.ajaxData = []

	//引用 layui
	this.layui = layui;
	this.form =  layui.form;
	this.table = layui.table;

	// 提交
	this.form.on('submit(formDemo)', function (data) {

		var reimDto = {};
		reimDto = data.field;
		var formlist = $('form').serializeArray();

		$.each(formlist, function () {
			reimDto[this.name] = this.value;
		});

		var reimUserid = $('select[name=reimUserid]').next().children('.chosen-single').children('span').text()
		for(var i=0;i<reimUseridlist.length;i++){

			if(reimUseridlist[i].name == reimUserid){
				reimDto.reimUserid = reimUseridlist[i].userId
			}
		}

		var deptIdl = $('select[name=deptId]').next().children('.chosen-single').children('span').text()
		for(var i=0;i<deptIdlist.length;i++){
			if(deptIdlist[i].name == deptIdl){
				reimDto.deptId = deptIdlist[i].deptId
			}
		}

		for (var i = 0; i < that.options.data.length; i++) {
			delete(that.options.data[i].LAY_TABLE_INDEX)
			for(var item in that.options.data[i]){
				var listsi = "reimInfoDOList["+ i +"]."+ item
				reimDto[listsi] = that.options.data[i][item]

			}
		}
		$.ajax({
			cache : true,
			type : "POST",
			url : "/fin/reim/save",
			data : reimDto,// 你的formid
			async : false,
			error : function(request) {
				parent.layer.alert("Connection error");
			},
			success : function(data) {
				if (data.code == 0) {
					parent.layer.msg("操作成功");
					parent.reLoad();
					var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
					parent.layer.close(index);

				} else {
					parent.layer.alert(data.msg)
				}

			}
		});
		return false; //阻止表单跳转
	});

	this.initOption = function(ele,data){
		var options = "<option value=''>请选择</option>";
		data.forEach(function (item,index) {
			options += "<option value=\"" + item.id + "\">" + item.name +"</option>";
		})

		ele.append(options);
		this.form.render('select')

		return this

	};
	this.getData = function(index,url){
		var option = ''
		if(!this.ajaxData[index]){
			$.ajax({
				type:"get",
				url:that.url[index],
				success:sucBack,
				error:function(){
					console.log("请求失败")
				}
			})
			//<dd lay-value="22" class="">项目报销/业务招待费</dd>
			function sucBack(data){
				that.ajaxData[index] = data
				that.initOption($(that.eleSelect[index]),data).setSelectVal(that.selectName[index]).updateSelect(that.eleSelect[index],that.selectName[index]);
				if(index == 1 ){
					selectData = data;

				}
			}
		}else{
			that.initOption($(that.eleSelect[index]),that.ajaxData[index]).setSelectVal(that.selectName[index]).updateSelect(that.eleSelect[index],that.selectName[index])
		}
	};
	this.renderSelect = function(params){
		if(!this.eleSelect  &&  !this.url && !this.selectName ){
			this.eleSelect= params.el
			this.url= params.url
			this.selectName= params.select
		}


		if(this.eleSelect&&!this.eleSelect.length){
			return
		}
		if(this.url&&!this.url.length){
			return
		}
		if(this.selectName&&!this.selectName.length){
			return
		}

		this.layui.use('form', function () {
			that.url.forEach(function(url,index){
				that.getData(index,url)
			})

		})
		return this

	};
	this.setSelectVal = function(ele){
		this.form.on('select('+ele+ ')', function(obj){
			var elem = obj.othis.parents('tr');
			var dataindex = elem.attr("data-index");
			$.each(that.options.data,function(index,value){
				if(value.LAY_TABLE_INDEX==dataindex){
					value[ele] = obj.value;
				}
			});

			//下拉框发送变化
			if (ele == "invoiceType") {
				$.each(selectData, function (index, value) {
					if (value.id == obj.value) {
						that.options.data[dataindex].taxRate = value.taxRate
					}
				})
				//that.options.data[dataindex].notTaxPrice = that.options.data[dataindex].reimPrice * that.options.data[dataindex].taxRate;
				//  if(that.options.data[dataindex].reimPrice == ''||that.options.data[dataindex].reimPrice == undefined){
				// 	 that.options.data[dataindex].notTaxPrice = 0
				//  }else{
				// 	 that.options.data[dataindex].notTaxPrice = (that.options.data[dataindex].reimPrice /(1+that.options.data[dataindex].taxRate)*that.options.data[dataindex].taxRate).toFixed(2);
				//  }
				that.table.render(that.options);
				that.renderSelect()
			}

		});

		return this
	};
	this.updateSelect = function(ele,name){

		$.each(this.options.data,function(index,value){
			$(ele).eq(index).val(value[name])
		});
		this.form.render('select')

		return this
	};
	this.initRowDouble = function(id){

		this.table.on("rowDouble("+id+")", function (obj) {

			var data1 = {
				amountTypeid:22,
				invoiceType:6,
				taxRate:0
			};
			that.options.data.push(data1);
			console.log(that.options.data,'dddddddd------ddddddd')
			that.table.render(that.options);

			that.renderSelect()

		});
		// 金额发送变化
		this.table.on("edit(" + id + ")", function (obj) {
			var editindex = $("tr").index(obj.tr);
			editindex = editindex - 1
			var newreimPrice = 0
			for(var i=0;i<that.options.data.length;i++){
				console.log(that.options.data[i].reimPrice,i,"999")
				if(!that.options.data[i].reimPrice){
					newreimPrice += 0
				}else {
					newreimPrice += Number(that.options.data[i].reimPrice)
				}
			}
			// $('#reimAmount').val(newreimPrice)
			$('#reimAmount').val(newreimPrice.toFixed(2))
			if (obj.field == "reimPrice") {
				// if (that.options.data[editindex].taxRate == ''|| that.options.data[editindex].taxRate == undefined ) {
				// 	that.options.data[editindex].notTaxPrice = that.options.data[editindex].reimPrice;
				// } else {
				// 	// that.options.data[editindex].notTaxPrice = (that.options.data[editindex].reimPrice - that.options.data[editindex].reimPrice *that.options.data[editindex].taxRate).toFixed(4);
				// 	that.options.data[dataindex].notTaxPrice = (that.options.data[dataindex].reimPrice /(1+that.options.data[dataindex].taxRate)*that.options.data[dataindex].taxRate).toFixed(2);
				// }

				that.table.render(that.options);
				that.renderSelect()
			}

		});

		return this
	};

	this.renderTable = function(name,open){
		console.log("---------")
		this.layui.use('table', function (obj) {
			that.table.render(that.options);
			open = open || false
			if(open){
				that.initRowDouble(name)
			}
		});
		return this
	}
}


var paramsSelect = {
	url:[
		'/fin/pricetype/priceTypelist',
		'/fin/reimburseType/reimtypelist',
		'/itm/project/getNotEndProjectlist',
	],
	el:[".chosen-select-amountTypeid",".chosen-select-invoiceType",".chosen-select-projectId"],
	select:['amountTypeid','invoiceType','projectId']
}

var select =new tableSelect(layui,opentls).renderTable("test",true).renderSelect(paramsSelect);
console.log(select,'select add')